package com.example.stray_animal_management_system.commonu.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.stray_animal_management_system.commonu.service.AdoptionService;
import com.example.stray_animal_management_system.commonu.service.AnimalService;
import com.example.stray_animal_management_system.entity.Adoption;
import com.example.stray_animal_management_system.entity.Animal;
import com.example.stray_animal_management_system.entity.User;
import com.example.stray_animal_management_system.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @description:
 * @author: panpan
 * @time: 2025/11/1
 */
@RestController
@RequestMapping("/api/adoption")
@CrossOrigin
public class AdoptionController {

    @Autowired
    private AdoptionService adoptionService;

    @Autowired
    private AnimalService animalService;
    @Autowired
    private UserService userService;

    /**
     * 用户提交领养申请
     */
    @PostMapping("/apply")
    public Map<String, Object> apply(@RequestBody Adoption adoption) {
        Map<String, Object> res = new HashMap<>();

        User user = userService.getById(adoption.getUserId());
        if (user == null) {
            res.put("code", 404);
            res.put("msg", "用户不存在");
            return res;
        }

        // 检查是否存在“待审核”的申请（不是驳回的）
        long pendingCount = adoptionService.lambdaQuery()
                .eq(Adoption::getUserId, adoption.getUserId())
                .eq(Adoption::getStatus, 0) // ✅ 待审核
                .count();
        if (pendingCount > 0) {
            res.put("code", 400);
            res.put("msg", "您已有待审核的申请，请等待审核完成后再申请");
            return res;
        }

        // 检查当月申请次数
        YearMonth currentMonth = YearMonth.now();
        LocalDateTime start = currentMonth.atDay(1).atStartOfDay();
        LocalDateTime end = currentMonth.atEndOfMonth().atTime(23, 59, 59);

        long monthlyCount = adoptionService.lambdaQuery()
                .eq(Adoption::getUserId, adoption.getUserId())
                .between(Adoption::getApplyTime, start, end)
                .count();

        if (monthlyCount >= user.getAdoptionQuota()) {
            res.put("code", 400);
            res.put("msg", "本月领养申请次数已达上限，请联系管理员增加额度。");
            return res;
        }

        // 保存申请
        adoption.setStatus(0); // 待审核
        adoption.setApplyTime(LocalDateTime.now());
        adoptionService.save(adoption);

        // 将动物状态改为“审核中”
        animalService.update(
                new UpdateWrapper<Animal>()
                        .eq("id", adoption.getAnimalId())
                        .set("status", 2) // 2=审核中
        );

        res.put("code", 200);
        res.put("msg", "申请提交成功，等待审核。");
        res.put("timestamp", System.currentTimeMillis());
        return res;
    }

    /**
     *  用户查看自己的申请记录
     *
     *  */
    @GetMapping("/user/{userId}")
    public Map<String, Object> listByUser(@PathVariable Integer userId) {
        List<Adoption> list = adoptionService.lambdaQuery()
                .eq(Adoption::getUserId, userId)
                .orderByDesc(Adoption::getApplyTime)
                .list();

        Map<String, Object> res = new HashMap<>();
        res.put("code", 200);
        res.put("msg", "查询成功");
        res.put("data", list);
        return res;
    }

    /**
     *
     * 用户修改申请
     * */
    @PutMapping("/update")
    public Map<String, Object> update(@RequestBody Adoption adoption) {
        Map<String, Object> res = new HashMap<>();
        Adoption db = adoptionService.getById(adoption.getId());
        if (db == null || db.getStatus() != 0) {
            res.put("code", 400);
            res.put("msg", "当前申请不可修改");
            return res;
        }

        adoptionService.updateById(adoption);
        res.put("code", 200);
        res.put("msg", "修改成功");
        return res;
    }

    /**
     * 用户撤回申请
     *
     * */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> delete(@PathVariable Integer id) {
        Map<String, Object> res = new HashMap<>();

        Adoption adoption = adoptionService.getById(id);

        if (adoption == null || adoption.getStatus() != 0) {
            res.put("code", 400);
            res.put("msg", "该申请不可删除");
            return res;
        }

        // 获取动物ID（在删除前保存）
        Integer animalId = adoption.getAnimalId();

        // 删除申请记录
        adoptionService.removeById(id);

        // 将动物状态改回可领养状态（status = 0）
        if (animalId != null) {
            try {
                Animal animal = animalService.getById(animalId);
                if (animal != null) {
                    animal.setStatus(0); // 0: 待领养
                    animalService.updateById(animal);
                }
            } catch (Exception e) {
                // 即使更新动物状态失败，申请删除已经成功
                e.printStackTrace();
                System.err.println("撤回申请时更新动物状态失败，animalId: " + animalId);
            }
        }

        res.put("code", 200);
        res.put("msg", "删除成功");
        return res;
    }
}